package com.WISSC.controller;

import com.WISSC.bean.*;
import com.WISSC.bean.layuiBean.ResultPage;
import com.WISSC.commen.BaseController;
import com.WISSC.service.ConfigureService;
import com.WISSC.service.StudentImageService;
import com.WISSC.service.StudentService;
import com.WISSC.service.WebPageService;
import com.WISSC.util.PageResult;
import com.WISSC.util.Respons.ResponseUtil;
import com.WISSC.util.date.DateUtil;
import com.WISSC.util.file.DownLoadFileUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 学员信息
 * </p>
 *
 * @author 张凯
 * @since 2019/5/5
 */
@Controller
@RequestMapping("/student")
@Api(value = "轮滑等级考核 controller", tags = "轮滑等级考核")
public class StudentController extends BaseController {

    @Autowired
    StudentService studentService;

    @Autowired
    StudentImageService studentImageService;

    @Autowired
    WebPageService webPageService;

    @Autowired
    ConfigureService configureService;

    //首页
    @RequestMapping(value = "student.html", method = RequestMethod.GET)
    public String main() {
        return "main/student";
    }

    //学员添加
    @RequestMapping(value = "student_add.html", method = RequestMethod.GET)
    public String student_add() {
        return "add/student_add";
    }

    //学员编辑
    @RequestMapping(value = "student_edit.html", method = RequestMethod.GET)
    public String student_edit(Model model, Long id, String url, String stuId) {
        model.addAttribute("id", id);
        model.addAttribute("url", url);
        model.addAttribute("stuId", stuId);
        return "edit/student_edit";
    }

    //证书
    @RequestMapping(value = "certificate.html", method = RequestMethod.GET)
    public String certificate(Student student, Model model, PageResult p) {
        int num = studentService.getCount(student.getIdNumber(), student.getIdNo());
        PageResult pr = new PageResult(p.getCurPage(), num);

        Map<String, Object> map = new HashMap<>();
        map.put("p", pr);
        map.put("idNumber", student.getIdNumber());
        map.put("idNo", student.getIdNo());
        List<Student> list = studentService.getManyUrl(map);
        List<Student> list2 = studentService.getStudentCount(student.getIdNumber(), student.getIdNo());
        List list1 = new ArrayList();
        for (int i = 0; i < list2.size(); i++) {
            list1.add(i + 1);
        }
        model.addAttribute("list", list);
        model.addAttribute("list1", list1);
        model.addAttribute("idNo", student.getIdNo());
        model.addAttribute("idNumber", student.getIdNumber());
        model.addAttribute("p", pr);
        return "grade/certificate";
    }


    //学员查询登陆页面
    @RequestMapping(value = "student_login.html", method = RequestMethod.GET)
    public String student_login() {

        return "student_login";
    }

    //学员查询首页
    @RequestMapping(value = "student_index.html", method = RequestMethod.GET)
    public String student_index(Student student, Model model) {
        Integer count = studentService.getCount(student.getIdNumber(), student.getIdNo());
        model.addAttribute("idNumber", student.getIdNumber());
        model.addAttribute("idNo", student.getIdNo());
        model.addAttribute("count", count);
        model.addAttribute("list", webPageService.selectAll());
        model.addAttribute("url", configureService.getById(1).getConfigure());
        return "student_index";
    }

//    //轮滑等级证书 --多证书显示
//    @RequestMapping(value = "getManyUrl", method = {RequestMethod.GET, RequestMethod.POST})
//    @ResponseBody
//    public Map getManyUrl(Model model,Student student) {
//        String idNumber = student.getIdNumber();
//        String idNo = student.getIdNo();
////        Map map = studentService.getManyUrl(idNo,idNumber);
//        return map;
//    }

    //空页面
    @RequestMapping(value = "nopicture.html", method = RequestMethod.GET)
    public String noPicture() {

        return "nopicture";
    }

    /**
     * @param file
     * @return 多文件上传 配合添加使用
     * @throws Exception
     */
    @RequestMapping("/upload")
    @ResponseBody
    public Massage upload(@RequestParam("file") MultipartFile file) {

        return studentImageService.upload(file);
    }

    // 编辑图片的的修改
    @RequestMapping("/updateimageUrl")
    @ResponseBody
    public Massage updateimageUrl(@RequestParam("file") MultipartFile file, @RequestParam("stuId") String stuId, HttpSession session) {
        if (getUser(session).getStatus() == 2) {
            return studentImageService.updateimageUrl(file, stuId);

        } else {
            return studentImageService.upload(file);
        }
    }

    /**
     * @param studentId
     * @return 多图片编辑
     * @throws Exception
     */
    @RequestMapping("/updatePicture")
    @ResponseBody
    public Massage updatePicture(String studentId, @RequestParam("file") MultipartFile file) {
        return studentImageService.updatePicture(studentId, file);
    }


    /**
     * @param param1
     * @param pIds
     * @return 学员信息添加
     */
    @RequestMapping(value = "studentInsert", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("学员信息添加")
    public String studentInsert(String param1, String[] pIds, String param2, HttpSession session) {
        Student student = JSONObject.parseObject(param1, Student.class);
        if (getUser(session).getStatus() == 2) {
            student.setType(1);
            student.setFlag(4);
        } else {
            student.setType(2);
            student.setFlag(1);
        }
        return studentService.studentInsert(student, pIds, param2);
    }

    /**
     * @param page
     * @param limit
     * @param name
     * @param idNumber
     * @param regTime
     * @param city
     * @param subject
     * @param subjectLevel
     * @return 查询 + 分页
     */
    @RequestMapping(value = "selectMyPage", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("学员信息查询")
    public ResultPage<Student> selectMyPage(

            @ApiParam(name = "page", value = "页码", required = true)
            @RequestParam int page,
            @ApiParam(name = "limit", value = "查询条数", required = true)
            @RequestParam int limit, String name, String idNumber, Long regTime,
            String city, Integer subject, Integer subjectLevel, HttpSession session
    ) {
        boolean admin = false;
        if (getUser(session).getRoles().getRoleValue().equals("9f77d5a8-75c6-4d06-adf9-a37e727d491a")) {
            admin = true;
        }
        return studentService.selectMyPage(page, limit, name, idNumber, regTime, city, subject, subjectLevel, admin);
    }

    /**
     * @param student
     * @return 学员信息删除
     */
    @RequestMapping(value = "studentDelete", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("学员信息删除")
    public Map studentDelete(@RequestBody Student student, HttpSession session) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("student_id",student.getId());
        List<StudentImage> studentImage = studentImageService.list(wrapper);
        for (int i = 0; i < studentImage.size(); i++) {
            File file = new File(studentImage.get(i).getImageUrl());
            if (file.isFile() && file.exists()) {
                file.delete();
            }
        }

        if (getUser(session).getStatus() == 2) {
            if (studentService.removeById(student)) {
                if (studentImageService.removeByStudentId(student.getId())) {
                    return ResponseUtil.getSuccessMap();
                }
            }
        } else {
            student.setType(2);
            student.setFlag(2);
            studentService.updateById(student);
            return ResponseUtil.getSuccessMap();
        }
        return ResponseUtil.getExceptionMap();
    }

    /**
     * @return 学员信息编辑
     */
    @RequestMapping(value = "updateById", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("学员信息修改")
    public Map update(String param1, String[] pIds, String param2, HttpSession session) {
        Student student = JSONObject.parseObject(param1, Student.class);
        if (getUser(session).getStatus() == 2) {
            student.setType(1);
            student.setFlag(4);
            return studentService.updateStudent(student, param2);
        } else {
            Student t = new Student();
            t.setName(student.getName());
            t.setSex(student.getSex());
            t.setIdNumber(student.getIdNumber());
            t.setRegTime(student.getRegTime());
            t.setBeforeId(student.getId());
            t.setCity(student.getCity());
            t.setFlag(3);
            t.setType(2);
            String[] split = param2.split("@");
            List list = new ArrayList();
            for (int j = 0; j < split.length; j++) {
                list.add(split[j]);
            }
            String param3 = "";
            for (int j = 0; j < list.size(); j++) {
                String arr = (String) list.get(j);
                String[] str = arr.split(",");
                param3 += str[1] + "," + str[2] + "," + str[3] + "-";
            }
            String arr = "";
            if (pIds[0].equals("kk")) {
                List<StudentImage> list1 = studentImageService.getBystuId(student.getId());
                for (int i = 0; i < list1.size(); i++) {
                    StudentImage studentImage = new StudentImage();
                    studentImage.setImageUrl(list1.get(i).getImageUrl());
                    studentImage.setFileName(list1.get(i).getFileName());
                    studentImage.setCreateTime(DateUtil.date());
                    studentImageService.save(studentImage);
                    arr += studentImage.getId() + ",";
                }
            }
            String[] sss = arr.split(",");
            studentService.studentInsert(t, sss, param3);
            return ResponseUtil.getSuccessMap();
        }

    }


    @RequestMapping(value = "getTeamCity", method = RequestMethod.POST)
    @ResponseBody
    public Map getTeamCity(Long id) {
        return studentService.getTeamCity(id);
    }

    //图片下载
    @RequestMapping(value = "Download")
    @ResponseBody
    public void Download(HttpServletResponse response, Long id) {
        StudentImage studentImage = studentImageService.getById(id);
        String url = studentImage.getImageUrl();
        String filename = studentImage.getFileName();
        DownLoadFileUtils.downloadFile(response, url, filename);
    }


    //通过
    @RequestMapping(value = "adopt", method = RequestMethod.POST)
    @ResponseBody
    public Map abopt(@RequestBody Student student) {
        Student t = studentService.getById(student);
        if (t.getFlag() == 2) {
            if (studentService.removeById(student) && studentImageService.removeByStudentId(t.getId())) {
                return ResponseUtil.getSuccessMap();
            }
        } else if (t.getFlag() == 1) {
            student.setType(1);
            student.setFlag(4);
            if (studentService.updateById(student)) {
                return ResponseUtil.getSuccessMap();
            }
        } else {
            student.setType(1);
            student.setFlag(4);
            studentService.updateById(student);
            if (studentService.removeById(t.getBeforeId()) && studentImageService.removeByStudentId(t.getBeforeId())) {
                return ResponseUtil.getSuccessMap();
            }
        }
        return ResponseUtil.getExceptionMap();
    }

    //不通过
    @RequestMapping(value = "noAdopt", method = RequestMethod.POST)
    @ResponseBody
    public Map noAdopt(@RequestBody Student student) {

        Student t = studentService.getById(student);
        if (t.getFlag() == 2) {
            t.setFlag(4);
            t.setType(1);
            if (studentService.updateById(t)) {
                return ResponseUtil.getSuccessMap();
            }

        } else if (t.getFlag() == 1) {
            if (studentService.removeById(student) && studentImageService.removeByStudentId(student.getId())) {
                return ResponseUtil.getSuccessMap();
            }
        } else {
            if (studentService.removeById(student) && studentImageService.removeByStudentId(student.getId())) {
                return ResponseUtil.getSuccessMap();
            }
        }

        return ResponseUtil.getExceptionMap();
    }

    //批量删除
    @RequestMapping(value = "deleteBtId", method = RequestMethod.POST)
    @ResponseBody
    public Map deleteById(String ids, HttpSession sessions) {
        String[] a = ids.split(",");
        for (int i = 1; i < a.length; i++) {
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("student_id",a[i]);
            List<StudentImage> studentImage = studentImageService.list(wrapper);
            for (int j = 0; j < studentImage.size(); j++) {
                File file = new File(studentImage.get(j).getImageUrl());
                if (file.isFile() && file.exists()) {
                    file.delete();
                }
            }
        }
        if (getUser(sessions).getStatus() == 2) {
            for (int i = 1; i < a.length; i++) {
                studentService.removeById(a[i]);
                Student student = new Student();
                student.setId(Long.parseLong(a[i]));
                studentImageService.removeByStudentId(student.getId());
            }
            return ResponseUtil.getSuccessMap();
        } else {
            for (int i = 1; i < a.length; i++) {
                Student student = new Student();
                student.setId(Long.parseLong(a[i]));
                student.setType(2);
                student.setFlag(2);
                studentService.updateById(student);
            }
            return ResponseUtil.getSuccessMap();

        }
    }

    //不通过和删除信息用的用一个方法    删除时候删除主表和关联表的数据
    @RequestMapping(value = "deleteByIdStudent", method = RequestMethod.POST)
    @ResponseBody
    public Integer deleteByIdStudent(Long id) {

        return studentService.deleteByIdStudent(id);
    }
}
